package com.example.forum.services.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServicesImpl implements IArticleServices {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private UserServicesImpl userServices;
    @Resource
    private BoardServicesImpl boardServices;

    //新增文章
    @Override
    public int create(Article article) {

        //参数校验
        if (article == null) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        //新增文章
        System.out.println("c++test:  " + article);
        int result = articleMapper.insert(article);
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //相应board下帖子数量+1
        if (boardServices.addOneArticleCountById(article.getBoardId()) == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //相应user下帖子数量+1
        if (userServices.addOneArticleCountById(article.getUserId()) == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return result;
    }

    @Override
    public boolean updateArticle(Article article) {
        if (article == null) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        int result = articleMapper.updateByPrimaryKeySelective(article);
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE));
            log.error(e.getStackTrace().toString());
            throw e;

        }
        return true;
    }

    @Override
    public List<Article> selectAll() {
        //查询
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if (boardId == null || boardId <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //校验板块是否存在
        Board result = boardServices.selectByPrimaryKey(boardId);
        if (result == null) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //查询该板块下的所有帖子
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //查询
        Article article = articleMapper.selectDetailById(id);

        if (article != null) {
            //帖子浏览数+1
            if (articleMapper.updateVisitCountById(id) != 1) {
                ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
                log.error(e.getStackTrace().toString());
                throw e;
            } else {
                article.setVisitCount(article.getVisitCount() + 1);
                return article;
            }
        }
        ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        log.error(e.getStackTrace().toString());
        throw e;
    }

    //更新帖子内容
    @Override
    public boolean modify(Long id, String title, String content) {
        //参数校验
        if (id == null || id <= 0 ||
                title == null || title.trim().equals("") ||
                content == null || content.trim().equals("")) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //封装帖子内容
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setId(id);
        article.setUpdateTime(new Date());
        //更新
        Integer result = articleMapper.updateByPrimaryKeySelective(article);

        //更新成功 后 浏览次数+1
        if (result == 1) {
            if (articleMapper.updateVisitCountById(id) == 1)
                return true;
        }
        ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE));
        log.error(e.getStackTrace().toString());
        throw e;
    }

    //
    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //参数校验
        if (userId == null || userId <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //校验用户是否存在
        User user = userServices.selectById(userId);
        if (user == null) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //调用mapper
        List<Article> articles = articleMapper.selectByUserId(userId);

        return articles;
    }

    //点赞
    @Override
    public boolean thumbsUpById(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //获取帖子情况
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //判断帖子状态
        if (article.getDeleteState() == 1 || article.getState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //更新点赞数
        int likeCount = article.getLikeCount() + 1;
        article.setLikeCount(likeCount);
        article.setUpdateTime(new Date());
        //更新帖子
        int result = articleMapper.updateByPrimaryKeySelective(article);

        //判断是否跟新成功
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return true;
    }

    @Override
    public Integer delete(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //查询要删除的帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //构建更新对象
        Article updateArticle = new Article();
        updateArticle.setUpdateTime(new Date());
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);


        //调用dao 更新帖子
        Integer result = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.getStackTrace().toString());
            throw e;
        }


        //相应board下帖子数量-1
        if (boardServices.subOneArticleCountById(article.getBoardId()) == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //相应user下帖子数量-1
        if (userServices.subOneArticleCountById(article.getUserId()) == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        return result;
    }

    @Override
    public Integer addOneReplyCountById(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);

        //校验帖子状态是否正常
        if (article == null || article.getDeleteState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //校验帖子是否封贴
        if (article.getState() == 1) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //构建 回复数更新 对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);

        //更新
        Integer result = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return result;
    }
    //根据帖子标题关键字查询
    public List<Article> selectAllByTitle(String key){
        //参数校验
        if (key == null){
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //查询
        return articleMapper.selectByArticleName(key);
    }



    public List<Article> selectAllByContent(String key){
        //参数校验
        if (key == null){
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        return articleMapper.selectByArticleContent(key);
    }
}
